//
//  HORecordActiveView.m
//  Huahai
//
//  Created by Fox Guo on 14-10-20.
//
//

#import "HORecordActiveView.h"
//#import "MacroUtils.h"
#import "Logger.h"
#import "HOUtils.h"
//#import "WebImageOperations.h"
//#import "BigController.h"
#import "HODefaultImage.h"
#import "HOAudioPlayer.h"
@interface HORecordActiveView()
{
	int indicateImgIndex;
}
@end

@implementation HORecordActiveView
//-(id)initWithFrame:(CGRect)frame withSuper:(UIView *)view
//{
//    if(self = [super initWithFrame:frame])
//    {
//        selfSuperView = view;
//        audioRecorder = [[AudioRecorder alloc] initWithDelegate:self];
//        [self initUI];
//    }
//    return self;
//        
//}
-(id)initWithFrame:(CGRect)frame
{
    if(self = [super initWithFrame:frame])
    {
        selfSuperView = self;
        audioRecorder = [[AudioRecorder alloc] initWithDelegate:self];
        [self initUI];
    }
    return self;
}
- (void)initUI
{
    [self setBackGround];
    [self addImage];
    [self addAlertLabel];
    [self addErroImage];
    [self addCancleImage];
    [self addVolumeImg];
}
//-(instancetype)initWithFrame:(CGRect)frame
//{
//    self = [super initWithFrame:frame];
//    if (self) {
//        [self setBackGround];
//        [self addImage];
//        [self addAlertLabel];
//        [self addVolumeImg];
//    }
//    return self;
//}
-(void)setBackGround
{
    self.backgroundColor = UIColorFromRGB(0x000000);
    self.layer.cornerRadius = 4;
    self.alpha = 0.5;
    self.layer.masksToBounds = YES;
}
-(void)addImage
{
    interPhoneImgView = [[UIImageView alloc] initWithFrame:CGRectMake(36, 25, 41, 68)];
    interPhoneImgView.image = [UIImage imageNamed:@"microphone.png"];
    [self addSubview:interPhoneImgView];
}
-(void)addErroImage
{
    errorRecordImgView = [[UIImageView alloc] initWithFrame:CGRectMake(36+13.5 + 13, 25+2.5, 14, 62.5)];
    errorRecordImgView.image = [UIImage imageNamed:@"!.png"];
    [self addSubview:errorRecordImgView];
}
-(void)addCancleImage
{
    recordPauseImgView = [[UIImageView alloc] initWithFrame:CGRectMake(33 + 13, 25 + 3.5, 47, 61)];
    recordPauseImgView.image = [UIImage imageNamed:@"cancelRecording.png"];
    [self addSubview:recordPauseImgView];
}
-(void)addAlertLabel
{
    recordHintTxt = [[UILabel alloc] initWithFrame:CGRectMake(0, self.frame.size.height - 27, self.frame.size.width, 12)];
    recordHintTxt.font = [UIFont systemFontOfSize:12];
    recordHintTxt.textColor = UIColorFromRGB(0xffffff);
    recordHintTxt.textAlignment = NSTextAlignmentCenter;
    recordHintTxt.text = @"录制中,松开结束";
	self.textLbl.text = recordHintTxt.text;
    [self addSubview:recordHintTxt];
}
-(void)addVolumeImg
{
    volumnView = [[UIView alloc] initWithFrame:CGRectMake(87, 30, 26, 65)];
    volumnImgView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 26, 65)];
    volumnImgView.image = [UIImage imageNamed:@"volume9.png"];
    [volumnView addSubview:volumnImgView];
    [self addSubview:volumnView];
}
- (void)initAuditionUI
{
//    [self setCurrentViewDisclick];
    CGRect rect = [UIScreen mainScreen].bounds;
    auditionView = [[UIView alloc]initWithFrame:CGRectMake(30, 130, 216, 160)];
    auditionView.center = CGPointMake(rect.size.width/2, rect.size.height/2-80);
    auditionView.backgroundColor = [UIColor lightGrayColor];
//    [auditionView setBackgroundColor:[UIColor colorWithPatternImage:[Utils imageNamed:@"bg_record"]]];
    [auditionView setHidden:YES];
    //    view.backgroundColor=[UIColor blackColor];
    auditionView.alpha=0.0;
    auditionView.layer.cornerRadius = 10; //圆角背景
    [selfSuperView addSubview:auditionView];
    
    [UIView beginAnimations:nil context:nil];
    auditionView.alpha = 1.0;
    [UIView setAnimationDuration:0.8];
    [UIView commitAnimations];
    
}
- (void)alertDisApper:(id)sender
{
    
}
-(void)showAlertWithTitle
{
    [auditionView setHidden:NO];
    
}
/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/


-(void)showNotificationForRecordTime:(NSTimeInterval)recordTime
{
	
	double remainTime = MAX_RECORDING_TIME - recordTime;
	if(remainTime == 0)
		return;
    NSString *content = [NSString stringWithFormat:@"剩余录音时间:%.0f秒", remainTime];
    
    [self.delegate popupHintView:content];
    
}

- (void)onDetectingVoice:(double)lowPassResults
{
    int index = 0;
    //    LogNor(@"onDetectingVoice:%lf",lowPassResults);
    if (0<lowPassResults<=0.06) {
        index = 0;
    }else if (0.13<lowPassResults<=0.20) {
        index = 1;
    }else if (0.27<lowPassResults<=0.34) {
        index = 2;
    }else if (0.41<lowPassResults<=0.48) {
        index = 3;
    }else if (0.55<lowPassResults<=0.62) {
        index = 4;
    }else if (0.69<lowPassResults<=0.76) {
        index = 5;
    }else if (0.83<lowPassResults<=0.9) {
        index = 6;
    }else {
        index = 0;
    }
    [self updateVolumnImg:index];
}
- (void)onStopRecord:(BOOL)isSuccessed totalTime:(NSTimeInterval)totalTime withFilePath:(NSString *)filePath withFileName:(NSString *)fileName
{
    [self hideRecordUI];
    if(!isSuccessed)
        return;
    LogNor(@"onStopRecord filePath:%@", filePath);
    NSData *audioData = [NSData dataWithContentsOfFile:filePath];
    if([audioData length] > 0 && isNeedSendAudio)
    {
        
        //        [self showAlertWithTitle:@"提示" onView:self.view];
    }

    
    [self.delegate submitVoiceWithFileName:fileName withTotalTime:totalTime];
    isNeedSendAudio = NO;
    
}

-(void)showAlertWithTitle:(NSString *)title onView:(UIView *)currentView
{
//    [self setCurrentViewDisclick];
    CGRect rect = [UIScreen mainScreen].bounds;
    UIView*view=[[UIView alloc]initWithFrame:CGRectMake(30, 130, 216, 160)];
    view.center = CGPointMake(rect.size.width/2, rect.size.height/2-80);
//    [view setBackgroundColor:[UIColor colorWithPatternImage:[Utils imageNamed:@"bg_record"]]];
    //    view.backgroundColor=[UIColor blackColor];
    view.alpha=0.0;
    view.layer.cornerRadius = 10; //圆角背景
    [currentView addSubview:view];
    
    [UIView beginAnimations:nil context:nil];
    view.alpha = 1.0;
    [UIView setAnimationDuration:0.8];
    [UIView commitAnimations];
	[view release];
}
- (void)stopTimer
{
    if(preTimer != nil)
    {
        [preTimer invalidate];
        preTimer = nil;
    }
}

-(void)sendAudio:(id)sender
{
    [self stopTimer];
//    [self setCurrentViewClick];
    UIView *view = [sender superview];
    [view removeFromSuperview];
    [self convertToamr:@""];
    
}
-(void)convertToamr:(NSString *)tagIDcontent
{
    // need check agin
//	[WebImageOperations ConvertSendAudioWithTagID:tagIDcontent andBlock:nil];
//    [WebImageOperations ConvertSendAudioWithTagID:tagIDcontent andBlock:^(BOOL isConvertSuccessed, NSData *data, NSError *error) {
//        
//        if(isConvertSuccessed)
//        {
////            [self.delegate submitVoice:data];
//        }
//    }
//     ];
}
- (void)hideRecordUI
{
    errorRecordImgView.hidden = YES;
    interPhoneImgView.hidden = YES;
    recordPauseImgView.hidden = YES;
    pauseRecordHintTxtBg.hidden = YES;
    volumnView.hidden = YES;
	self.hidden = YES;
	self.textLbl.text = @"手指上滑, 取消发送";

}
- (void)onStartRecord
{
	recordHintTxt.text = @"手指上滑,取消发送";
	self.textLbl.text = recordHintTxt.text;
    self.hidden = NO;
    errorRecordImgView.hidden = YES;
    interPhoneImgView.hidden = NO;
    volumnView.hidden = NO;
    pauseRecordHintTxtBg.hidden = YES;
    recordPauseImgView.hidden = YES;
}
- (void)onRecordMoreThanOneMinute
{
    isNeedSendAudio = YES;
    LogNor(@"stoprecord-----[audioRecorder getRecordingTime]:%f", [audioRecorder getRecordingTime]);
    [audioRecorder stopRecord];
    if([audioRecorder getRecordingTime] > MIN_RECORDING_TIME)
    {
        [self hideRecordUI];
    }
}
- (void)onRecordLessOneSecond:(BOOL)displayErrorUI
{
    
    self.hidden = !displayErrorUI;
    errorRecordImgView.hidden = !displayErrorUI;
    interPhoneImgView.hidden = YES;
    pauseRecordHintTxtBg.hidden = YES;
    recordPauseImgView.hidden = YES;
    volumnView.hidden = YES;
    recordHintTxt.hidden = NO;
    if(displayErrorUI)
    {
        [recordHintTxt setBackgroundColor:[UIColor clearColor]];
		recordHintTxt.text = @"录音时间太短";
        [pauseRecordHintTxtBg setBackgroundColor:[UIColor clearColor]];
		pauseRecordHintTxtBg.hidden = NO;
    }
    else
    {
		recordHintTxt.text = @"手指上滑,取消发送";
		self.textLbl.text = recordHintTxt.text;
	}
//        Imagetimer = [NSTimer scheduledTimerWithTimeInterval:1
//                                                      target: self
//                                                    selector: @selector(hideRecordUI)
//                                                    userInfo: nil
	//                                                     repeats: NO];
	self.textLbl.text = recordHintTxt.text;
	
	[self.delegate recordUIDidHide];
}

- (void)onErrorArise:(NSError *)error
{
    //Error
}
- (void)onPaused
{
    [self updateRecordHintText:YES];
}
- (void)onResumeRecord
{
    [self updateRecordHintText:NO];
}
- (void)updateRecordHintText:(BOOL )isCancelHiht
{
    if(isCancelHiht)
    {
        
        recordPauseImgView.hidden = NO;
        interPhoneImgView.hidden = YES;
        volumnView.hidden = YES;
        recordHintTxt.text = @"松开手指,取消发送";
        pauseRecordHintTxtBg.hidden = NO;
        recordHintTxt.font = [UIFont boldSystemFontOfSize:14];
        [recordHintTxt setBackgroundColor:[UIColor clearColor]];
    }
    else
    {
        
        recordPauseImgView.hidden = YES;
        interPhoneImgView.hidden = NO;
        pauseRecordHintTxtBg.hidden = YES;
        volumnView.hidden = NO;
        pauseRecordHintTxtBg.hidden = YES;
        [recordHintTxt setBackgroundColor:[UIColor clearColor]];
        recordHintTxt.text = @"手指上滑,取消发送";
        recordHintTxt.font = [UIFont systemFontOfSize:14];
	}
	self.textLbl.text = recordHintTxt.text;
}

- (void)startRecordAudio:(id)sender
{
    LogNor(@"startRecordAudio------------------");
//    [[[BigController getInstance] getMessageMgr] stopAudio];
    [audioRecorder startRecord];
}
- (void)resumeAudio:(id)sender
{
	LogNor(@"resumeAudio------------------");
    [audioRecorder resumeRecord];
}
- (void)stopRecordAudio:(id)sender
{
    isNeedSendAudio = YES;
    LogNor(@"stoprecord-----[audioRecorder getRecordingTime]:%f", [audioRecorder getRecordingTime]);
    [audioRecorder stopRecord];
    if([audioRecorder getRecordingTime] > MIN_RECORDING_TIME)
    {
        [self hideRecordUI];
    }
}
- (void)pauseRecordAudio:(id)sender
{
    isNeedSendAudio = NO;
    LogNor(@"pauseRecordAudio------------------");
    [audioRecorder pauseRecord];
}
- (void)stopRecordAudioDontSend:(id)sender
{
    LogNor(@"cancelAudio------------------");
    isNeedSendAudio = NO;
    [audioRecorder stopRecord];
    [self hideRecordUI];
}

- (void)updateVolumnImg:(int)index
{
    dispatch_queue_t callerQueue = dispatch_get_current_queue();
    dispatch_queue_t downloadQueue = dispatch_queue_create("com.huahai.processsmagequeue2", NULL);
    dispatch_async(downloadQueue, ^{
        if(index >= [[[HODefaultImage getInstance] getRecordingIndicateImgArray] count])
            return;
        UIImage * imageData = [[[HODefaultImage getInstance] getRecordingIndicateImgArray] objectAtIndex:index];
//        LogDbg(@"imageData:%@", imageData);
        dispatch_async(callerQueue, ^{
            if(imageData != nil)
            {
                volumnImgView.image = imageData;
                volumnImgView.frame = CGRectMake(0,
                                                 volumnView.frame.size.height - volumnImgView.image.size.height,
                                                 volumnView.frame.size.width,
                                                 volumnImgView.image.size.height);
            }
        });
    });
    
    
    
//    LogNor(@"updateVolumnImg 2");
}

- (void)updateTheVolumeImage
{
}

- (void)deleteTheVolume
{
}

- (void)begainToRecord
{
	LogNor(@"startRecordAudio------------------");
	//    [[[BigController getInstance] getMessageMgr] stopAudio];
	self.hidden = NO;
	[audioRecorder startRecord];
	
	
}

- (void)stopRecording
{
	isNeedSendAudio = YES;
	LogNor(@"stoprecord-----[audioRecorder getRecordingTime]:%f", [audioRecorder getRecordingTime]);
	[audioRecorder stopRecord];
	if([audioRecorder getRecordingTime] > MIN_RECORDING_TIME)
	{
		[self hideRecordUI];
	}
}
- (void)resumesRecording
{
	LogNor(@"resumeAudio------------------");
	[audioRecorder resumeRecord];
}

- (void)pauseRecording
{
	LogNor(@"pauseRecordAudio------------------");
	[audioRecorder pauseRecord];
}

- (void)canceleRecording
{
	LogNor(@"cancelAudio------------------");
	self.hidden = YES;
	[audioRecorder stopRecord];
	[self hideRecordUI];
}
@end
